local socket = require("socket")
local server = assert(socket.bind("*", 0))
local ip, port = server:getsockname()
print("Please telnet to localhost on port " .. port)
local all_read = {}
table.insert(all_read,server)
while 1 do
  local ready_forread
  ready_forread,_,_ = socket.select(all_read,nil,nil)
  for k,v in ipairs(ready_forread) do
    if v == server then
        print(" a new commer")
        local client = v:accept()
        table.insert(all_read,client)            
    else
        local line, err = v:receive()
        if line == nil then
            table.remove(all_read,k)
            v:close()
            print("a user disconnect")
        else
              print (line)
              if not err then
                  --下面检查套接口是否可写，如果可写就把文本发送回去
                  local for_write = {}
                  table.insert(for_write,v)
                  local ready_forwrite
                _,ready_forwrite,_ = socket.select(nil,for_write,1)    
                  if #ready_forwrite > 0 then
                      v:send(line .. "/n") 
                    print("send ok")
                  end
              end
          end
    end
  end
end
